/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.stateless;

import entity.ImageEntity;
import entity.StakeholderEntity;
import exception.ExistException;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Amelia
 */
@Stateless
@LocalBean
public class MediaSessionBean {

    @PersistenceContext
    private EntityManager entityManager;

    //Create by Amelia - For adding photos into the ImageEntity
    public boolean addImage(Long stakeholderID, String imgUrlList, String type) throws ExistException {
        StakeholderEntity stakeholder = entityManager.find(StakeholderEntity.class, stakeholderID);
        if (stakeholder == null) {
            return false;
        }
        ImageEntity media = new ImageEntity();
        media.setStakeholder(stakeholder);
        media.setCaption("");
        media.setType(type);
        media.setImageUrl(imgUrlList);
        entityManager.persist(media);
        return true;
    }

    //Created by Amelia - For retrieving photos into the ImageEntity
    public List<ImageEntity> getImage(Long stakeholderId) throws ExistException {
        Query query = entityManager.createQuery("SELECT i FROM Image i WHERE i.stakeholder.id =:stakeholderId");
        query.setParameter("stakeholderId", stakeholderId);
        return query.getResultList();
    }

    //Created by Amelia - For removing photos into the ImageEntity
    public boolean removeImage(ImageEntity[] imageList) throws ExistException {
        for (int i = 0; i < imageList.length; i++) {
            ImageEntity image = entityManager.find(ImageEntity.class, imageList[i].getId());
            entityManager.remove(image);
        }
        entityManager.flush();
        return true;
    }

    //Created by Amelia - For adding caption into the ImageEntity
    public boolean addImageCaption(ImageEntity image, String caption) throws ExistException {
        ImageEntity imageItem = entityManager.find(ImageEntity.class, image.getId());
        imageItem.setCaption(caption);
        entityManager.persist(imageItem);
        entityManager.flush();
        return true;
    }
}
